<template>
  <el-container class="layout-container">
    <!-- 左侧侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '200px'" class="sidebar-wrapper">
      <div class="logo-container">
        <span v-if="!isCollapse">便利店仓储系统</span>
        <span v-else>CMS</span>
      </div>

      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        router
        class="sidebar-menu"
      >
        <sidebar-item
          v-for="route in menuRoutes"
          :key="route.path"
          :item="route"
        />
      </el-menu>

      <div class="collapse-trigger" @click="isCollapse = !isCollapse">
        <el-icon :size="20">
          <component :is="isCollapse ? 'Expand' : 'Fold'" />
        </el-icon>
      </div>
    </el-aside>

    <!-- 右侧主区域 -->
    <el-container>
      <!-- 顶部头部 -->
      <el-header class="header-wrapper">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item
              v-for="item in breadcrumbList"
              :key="item.path"
              :to="item.path"
            >
              {{ item.meta?.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <div class="user-info">
              <el-avatar
                src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                size="small"
              />
              <span class="username">{{ userInfo?.name || "Admin" }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 标签页 -->
      <div class="tabs-wrapper">
        <el-tabs
          v-model="activeTab"
          type="card"
          closable
          @tab-remove="removeTab"
          @tab-click="clickTab"
        >
          <el-tab-pane
            v-for="tab in tabs"
            :key="tab.path"
            :name="tab.path"
            :label="tab.title"
          />
        </el-tabs>
      </div>

      <!-- 内容区域 -->
      <el-main class="main-wrapper">
        <router-view v-slot="{ Component }">
          <keep-alive :include="cachedViews">
            <component :is="Component" />
          </keep-alive>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useRoute, useRouter, type RouteRecordRaw } from "vue-router";
//   import { useAuthStore } from '@/store/auth'
import SidebarItem from "@/layouts/components/SidebarItem.vue";
// 在原有代码基础上修改watch部分和添加初始化方法
import { onMounted } from "vue";
// 在侧边栏组件中使用
import { generateSidebar } from "@/utils/routeGenerator";
import { buildMenuTree, generateRoutes } from "@/utils/routeGenerator";
import { mockMenuData } from "@/mock/menuData";

// 整理后端返回的菜单列表格式
const menuTree = buildMenuTree(mockMenuData);

// 将整理的格式转化为菜单可用的格式
const menuRoutes = generateSidebar(menuTree);

const route = useRoute();
const router = useRouter();

// 侧边栏折叠状态
const isCollapse = ref(false);

// 当前激活菜单
const activeMenu = computed(() => route.path);

// 标签页逻辑
const tabs = ref<Array<{ title: string; path: string }>>([]);
const activeTab = ref("");
const cachedViews = ref<string[]>([]);

// 初始化首页标签
const initHomeTab = () => {
  const homeRoute = router.resolve("/home");
  const homeTab = {
    title: homeRoute.meta.title || "首页",
    path: homeRoute.path,
  };

  if (!tabs.value.find((tab) => tab.path === homeTab.path)) {
    tabs.value = [homeTab];
    activeTab.value = homeTab.path;
  }
};

// 监听路由变化更新标签
watch(
  () => route.fullPath,
  (newVal) => {
    const { meta, path } = route;
    const title = meta.title || "未命名";

    // 添加标签页
    const exist = tabs.value.find((tab) => tab.path === path);
    if (!exist) {
      if (tabs.value.length >= 5) {
        tabs.value.shift();
      }
      tabs.value.push({ title, path });
    }

    activeTab.value = path;
    if (!cachedViews.value.includes(path)) {
      cachedViews.value.push(path);
    }
  },
  { immediate: true }
);

// 移除标签页
const removeTab = (targetPath: string) => {
  const targetTab = tabs.value.find((tab) => tab.path === targetPath);
  // 禁止关闭固定标签页
  if (targetTab?.meta?.affix) return;
  const index = tabs.value.findIndex((tab) => tab.path === targetPath);
  tabs.value.splice(index, 1);

  if (targetPath === activeTab.value) {
    const lastTab = tabs.value[tabs.value.length - 1];
    if (lastTab) {
      router.push(lastTab.path);
    } else {
      router.push("/home");
    }
  }
};

// 点击标签页
const clickTab = (tab: any) => {
  const path = tab.props.name;
  router.push(path);
};

// 面包屑导航
const breadcrumbList = computed(() => {
  return route.matched.filter((item) => item.meta?.title);
});

// 用户操作处理
const handleCommand = (command: string) => {
  if (command === "logout") {
    router.push("/login");
  }
};

// 初始化时检测
onMounted(() => {
  if (tabs.value.length === 0) {
    initHomeTab();
  }
});
</script>

<style scoped lang="scss">
.layout-container {
  height: 100vh;
  width: 100vw;

  .sidebar-wrapper {
    background-color: #304156;
    transition: width 0.3s;
    position: relative;
    overflow: auto;

    .logo-container {
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 18px;
      background-color: #2b2f3a;
    }

    .sidebar-menu {
      border-right: none;
      background-color: inherit;
      :deep(.el-menu-item) {
        color: #bfcbd9;
        &:hover {
          background-color: #263445;
        }
        &.is-active {
          background-color: #1890ff !important;
        }
      }
    }

    .collapse-trigger {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      cursor: pointer;
      position: sticky;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: #263445;
      &:hover {
        background-color: #1d2a36;
      }
    }
  }

  .header-wrapper {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #eee;

    .user-info {
      display: flex;
      align-items: center;
      cursor: pointer;
      .username {
        margin-left: 8px;
      }
    }
  }

  .tabs-wrapper {
    padding: 0 16px;
    background: #fff;
    :deep(.el-tabs__header) {
      margin: 0;
    }
  }

  .main-wrapper {
    background-color: #f5f7f9;
  }
}
</style>
